package cn.pku.sirx.snad.ads.util;

import java.io.StringWriter;
import java.io.Writer;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import cn.pku.sirx.snad.ad.model.AdDescription;

/**
 * @author WangXiao
 */
public abstract class FormatUtils {

	/**
	 * Format a list of ad descriptions to HTML codes.
	 * 
	 * @param adDescriptions
	 *            a list of ad descriptions to format
	 * @return ad HTML codes for impression
	 */
	public static String formatAds(List<AdDescription> adDescriptions) {
		/*
		 * context
		 */
		VelocityContext context = new VelocityContext();
		context.put("ads", adDescriptions);
		/*
		 * write
		 */
		Writer writer = new StringWriter(512);
		adTemplate.merge(context, writer);
		return writer.toString();
	}

	private static Template adTemplate;

	static {
		VelocityEngine engine = new VelocityEngine();
		engine.setProperty(Velocity.RESOURCE_LOADER, "class");
		engine
				.setProperty("class.resource.loader.class",
						"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		engine.init();
		adTemplate = engine.getTemplate("ad-template.vm", "UTF-8");
	}

}
